package com.ydh.company.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class MyAdvice {

    private Logger logger= LoggerFactory.getLogger(MyAdvice.class);
    /**
     * 切点
     */
    @Pointcut("execution(* com.ydh.company.controller.*Controller.*(..))")
    public void pointcut(){
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        //记录URL，请求方法，IP，请求的类名，请求的类中的方法名，参数
        //获取Request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //请求的UPL
        logger.info("URL={}",request.getRequestURI().toString());
        //请求的方法
        logger.info("请求方法={}",request.getMethod());
        //请求的IP
        logger.info("请求IP={}",request.getRemoteAddr());
        //请求的控制器类
        logger.info("class={}",joinPoint.getSignature().getDeclaringType().getName());
        //请求的控制器中的方法
        logger.info("classMethod={}",joinPoint.getSignature().getName());
        //请求参数
        logger.info("args={}", Arrays.toString(joinPoint.getArgs()));
    }
}
